package com.zjt.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * Created by IntelliJ IDEA.
 * User: xueyanbeijing
 * Date: 12-8-14
 * Time: PM7:50
 * To change this template use File | Settings | File Templates.
 */
public class ImageUtil {
    private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    /**
     * 保存图片文件
     *
     * @param fileData
     * @param savePath
     * @return
     * @throws Exception
     *
     * asdgadgdgsdg34t2345234
     * 2012/08/09/       /asdg/asdgadgdgsdg34t2345234.gif
     */
    public static String saveImage(byte[] fileData, String savePath) throws Exception {
        String hashedName = DigestUtils.md5Hex(fileData);
        String basePath = File.separator + hashedName.substring(0, 8);
        String picPath = basePath + File.separator + hashedName;
        FileUtils.forceMkdir(new File(savePath + basePath));

        String picSavePath = savePath + picPath + ".jpg";

        logger.info("picSavePath = " + picSavePath);
        File saveFile = new File(picSavePath);
        FileUtils.writeByteArrayToFile(saveFile, fileData);

        return picSavePath;
    }
}
